import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _isArray from "lodash/isArray";
import _isNil from "lodash/isNil";
import _isString from "lodash/isString";
var _excluded = ["lovCode", "params", "form", "multipleFlag", "fieldCode", "onChange"],
    _excluded2 = ["lovCode", "lovMappings", "form", "fieldCode"],
    _excluded3 = ["form", "fieldName", "textValue", "textField", "lovMappings", "onChange"];

/**
 * 个性化组件
 * @date: 2019-12-15
 */
import React, { useEffect, useState } from 'react';
import { Icon, Select, DatePicker, Checkbox, Switch, Radio } from 'antd';
import { DEFAULT_DATE_FORMAT } from "../../../utils/constants";
import Lov from "../../Lov";
import { getCurrentOrganizationId, getUserOrganizationId } from "../../../utils/utils";
import { queryMapIdpValue } from "../../../services/api"; // Option组件初始化

var Option = Select.Option;
export function FlexSelect(_ref) {
  var lovCode = _ref.lovCode,
      _ref$params = _ref.params,
      params = _ref$params === void 0 ? {} : _ref$params,
      form = _ref.form,
      multipleFlag = _ref.multipleFlag,
      fieldCode = _ref.fieldCode,
      oldOnChange = _ref.onChange,
      contentProps = _objectWithoutProperties(_ref, _excluded);

  var cache = window.CUSTOMIZECACHE || {};
  var cacheOptions = lovCode && cache[lovCode];

  var _useState = useState(cacheOptions || []),
      _useState2 = _slicedToArray(_useState, 2),
      selectOptionsDataSource = _useState2[0],
      setSelectOptionsDataSource = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var updateTriggers = [lovCode].concat(Object.keys(params), Object.values(params)).join(',');
  useEffect(function () {
    if (!cacheOptions) {
      setLoading(true);

      if (!window.CUSTOMIZECACHE) {
        window.CUSTOMIZECACHE = {};
      }

      window.CUSTOMIZECACHE[lovCode] = 'loading';
      queryMapIdpValue(_objectSpread({
        lovCode: lovCode
      }, params)).then(function () {
        var res = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var options = res && !res.failed && res.lovCode || [];
        setSelectOptionsDataSource(options);
        window.CUSTOMIZECACHE[lovCode] = options;
      }).catch(function () {
        window.CUSTOMIZECACHE[lovCode] = false;
      }).finally(function () {
        setLoading(false);
      });
    } else if (cacheOptions !== 'loading') {
      setSelectOptionsDataSource(cacheOptions);
    }
  }, [updateTriggers, cacheOptions]);

  var onChange = function onChange(v) {
    var value = v;

    if (multipleFlag && _isArray(v)) {
      value = v.length > 0 ? v.join(',') : undefined;
    } // eslint-disable-next-line no-unused-expressions


    typeof oldOnChange === 'function' && oldOnChange(value);
  };

  var value = contentProps.value,
      defaultValue = contentProps.defaultValue;
  var multipleConfig = multipleFlag === 1 ? {
    mode: 'multiple',
    defaultValue: _isNil(defaultValue) || defaultValue === '' ? [] : defaultValue.split(','),
    value: typeof value === 'string' && value !== '' ? value.split(',') : undefined
  } : undefined;
  return /*#__PURE__*/React.createElement(Select, Object.assign({
    allowClear: true
  }, contentProps, multipleConfig, {
    style: {
      width: '100%'
    },
    onChange: onChange
  }), loading || _isString(selectOptionsDataSource) ? /*#__PURE__*/React.createElement(Option, {
    key: "loading"
  }, /*#__PURE__*/React.createElement(Icon, {
    type: "loading"
  })) : selectOptionsDataSource.map(function (n) {
    return /*#__PURE__*/React.createElement(Option, {
      value: String(n.value)
    }, n.meaning);
  }));
}
export function FlexRadioGroup(_ref2) {
  var lovCode = _ref2.lovCode,
      _ref2$lovMappings = _ref2.lovMappings,
      lovMappings = _ref2$lovMappings === void 0 ? [] : _ref2$lovMappings,
      form = _ref2.form,
      fieldCode = _ref2.fieldCode,
      contentProps = _objectWithoutProperties(_ref2, _excluded2);

  var _useState5 = useState([]),
      _useState6 = _slicedToArray(_useState5, 2),
      radioOptionsDataSource = _useState6[0],
      setRadioOptionsDataSource = _useState6[1];

  useEffect(function () {
    queryMapIdpValue({
      lovCode: lovCode
    }).then(function () {
      var res = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      setRadioOptionsDataSource(res && !res.failed && res.lovCode || []);
    });
  }, [1]);

  var onChange = function onChange(v) {
    var record = radioOptionsDataSource.find(function (i) {
      return i.value === v.target.value;
    }) || {};
    form.setFieldsValue(_objectSpread(_objectSpread({}, lovMappings.reduce(function (pre, cur) {
      return _objectSpread(_objectSpread({}, pre), {}, _defineProperty({}, cur.targetCode, record[cur.sourceCode]));
    }, {})), {}, _defineProperty({}, fieldCode, v)));
  };

  return /*#__PURE__*/React.createElement(Radio.Group, Object.assign({}, contentProps, {
    style: {
      width: '100%'
    },
    onChange: onChange
  }), radioOptionsDataSource.map(function (n) {
    return /*#__PURE__*/React.createElement(Radio, {
      value: n.value
    }, n.meaning);
  }));
}
export function FlexLov(_ref3) {
  var form = _ref3.form,
      fieldName = _ref3.fieldName,
      textValue = _ref3.textValue,
      textField = _ref3.textField,
      _ref3$lovMappings = _ref3.lovMappings,
      lovMappings = _ref3$lovMappings === void 0 ? [] : _ref3$lovMappings,
      onChange = _ref3.onChange,
      rest = _objectWithoutProperties(_ref3, _excluded3);

  var innerOnChange = function innerOnChange(_, record) {
    for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
      args[_key - 2] = arguments[_key];
    }

    // eslint-disable-next-line no-unused-expressions
    typeof onChange === 'function' && onChange.apply(void 0, [_, record].concat(args));

    if (lovMappings.length > 0) {
      form.setFieldsValue(_objectSpread({}, lovMappings.reduce(function (pre, cur) {
        return _objectSpread(_objectSpread({}, pre), {}, _defineProperty({}, cur.targetCode, record[cur.sourceCode]));
      }, {})));
    }
  };

  return /*#__PURE__*/React.createElement(Lov, Object.assign({
    onChange: innerOnChange,
    code: rest.lovCode,
    textValue: textValue
  }, rest));
}
export function FlexDatePicker(options) {
  return /*#__PURE__*/React.createElement(DatePicker, Object.assign({
    format: DEFAULT_DATE_FORMAT
  }, options));
}
export function FlexCheckbox(options) {
  return /*#__PURE__*/React.createElement(Checkbox, Object.assign({
    checkedValue: 1,
    unCheckedValue: 0
  }, options));
}
export function FlexSwitch(options) {
  return /*#__PURE__*/React.createElement(Switch, Object.assign({
    checkedValue: 1,
    unCheckedValue: 0
  }, options));
}
export function FlexLink(options) {
  var linkTitle = options.linkTitle,
      linkHref = options.linkHref,
      linkNewWindow = options.linkNewWindow,
      form = options.form,
      _options$dataSource = options.dataSource,
      dataSource = _options$dataSource === void 0 ? {} : _options$dataSource;
  var newHref = linkHref || '';
  var newTitle = linkTitle || '';
  var mappings = newHref.match(/{([^{}]*)}/g);
  var titleMappings = newTitle.match(/{([^{}]*)}/g);
  var values = {};

  if (mappings || titleMappings) {
    values = _objectSpread(_objectSpread({}, dataSource), form && form.getFieldsValue());
  }

  if (mappings) {
    newHref = replace(mappings, values, newHref);
  }

  if (titleMappings) {
    newTitle = replace(titleMappings, values, newTitle);
  }

  return /*#__PURE__*/React.createElement("a", {
    href: newHref,
    target: linkNewWindow ? '_blank' : '_self',
    rel: "noopener noreferrer"
  }, newTitle);
}

function replace(mappings, values, targetString) {
  var newString = targetString;

  for (var i = 0; i < mappings.length; i++) {
    if (mappings[i] === '{organizationId}' || mappings[i] === '{tenantId}') {
      // eslint-disable-next-line no-continue
      continue;
    }

    var key = mappings[i].match(/{([^{}]*)}/)[1];
    var value = _isNil(values[key]) ? '' : values[key];
    newString = newString.replace("{".concat(key, "}"), value);
  }

  newString = newString.replace(/{organizationId}/, getCurrentOrganizationId());
  newString = newString.replace(/{tenantId}/, getUserOrganizationId());
  return newString;
}